'''
Author: Hugo
Date: 2022-03-25 08:25:05
LastEditTime: 2022-03-28 10:00:39
LastEditors: Please set LastEditors
Description: 
'''
from typing import (List, Dict, Tuple)
import pyvisflow as pvf
from pyvisflow.core.components import BoxContainer
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from plotting import (plot_bar, plot_heatmap)
from calc_func import (get_topn2cons, calc_pct_nd)
import data
import seaborn as sns


def block_daily_tracking():
    pvf.markdown('''# 概念指数每日跟踪''')

    pvf.markdown('''当日得分前五''')

    cols = pvf.cols(len(data.top5_bar))
    for col, (name, v) in zip(cols, data.top5_bar.iterrows()):
        create_card(col, name, v[0], v[1])

    pvf.markdown('''当日得分后五''')
    cols = pvf.cols(len(data.low5_bar))
    for col, (name, v) in zip(cols, data.low5_bar.iterrows()):
        create_card(col, name, v[0], v[1])


def block_index_momentum():

    pvf.markdown('''#概念指数动量''')

    pct_chg = data.pct_chg.dropna()
    tabs = pvf.tabs(pct_chg.columns)
    days = [col[:-1] for col in pct_chg.columns]

    # 遍历中就是每个子tab的内容
    for day, tab in zip(days, tabs.boxes):
        fig = plot_bar(pct_chg, '%s日' % day, title='%s日动量' % day)

        # 直接传入 fig
        tab.plotly().from_fig(fig)

    pvf.markdown('''## 动量得分前五 成分股情况''')

    # need {'5日':['3D打印','A',...],'10日':[...]}
    def largest_names(df: pd.DataFrame):
        return df.nlargest(5, 'value')['概念名称'].tolist()

    unpivot = data.pct_chg.reset_index().melt(id_vars='概念名称', var_name='day')
    mapping = unpivot.groupby('day').apply(largest_names).to_dict()

    # 概念前五的成分股
    code2sec = data.concept_dic[1]
    sec2code = {v: k for k, v in code2sec.items()}
    con2codes = data.concept_dic[0]
    price = data.top5_concept_price.copy()
    price.columns = price.columns.map(sec2code)
    pct_nchange_df = calc_pct_nd(price, [5, 10, 20, 60])

    ## tmp.loc[概念名称]及为所需的
    tmp = pd.concat({k: pct_nchange_df.loc[v] for k, v in con2codes.items()})
    tmp.index.names = ['概念', '股票代码']
    tmp.reset_index(inplace=True)

    # 设置动态下拉
    select_names = pvf.fns.map(tabs.activeName, mapping)

    select = pvf.select([])
    select.options = select_names
    table = pvf.dataTable(tmp)

    table.query(table['概念'] == select.currentLabels[0]
                )  #.sort_values(tabs.activeName,ascending=False).iloc[:5]

    # pvf.plotly().from_fig(plot_heatmap(data.show_wrs.iloc[-5:], '动量得分(加权)'))


def block_index_rot_score():

    pvf.markdown('''#概念指数轮动得分''')
    pvf.markdown('''##动量得分''')
    pvf.plotly().from_fig(plot_heatmap(data.show_wrs.iloc[-5:]))
    pvf.markdown('''##动量得分(加权)''')
    pvf.plotly().from_fig(plot_heatmap(data.show_rs.iloc[-5:]))


def create_card(ct: BoxContainer, desc: str, value: float, change: float):

    ct.styles.set_border().set_border_radius('0.5rem').set_margin(
        '0 1rem').set('padding', '1rem 1.5rem')
    ct.markdown(desc)

    # 左边普通数值，右边是上升或下降
    left, right = ct.cols(2)
    left.text('{:.2}'.format(value)).styles.set('color',
                                                'rgba(78, 70, 229)').set(
                                                    'font-size', '1.2rem')

    right.styles.set_border_radius().set_width('8rem').set(
        'padding', '0.2rem 0.8rem')

    icon = '向上'

    if change > 0:
        right.styles.set_background('rgba(254, 226, 226)')
    else:
        icon = '向下'
        right.styles.set_background('rgba(209, 250, 229)')

    left, right = right.cols([1, 2])
    left.styles.make_center()
    left.icon_fromfile(f'icons/箭头_{icon}.svg', '1rem')
    right.text('{:.2%}'.format(change)).styles


block_daily_tracking()
block_index_momentum()
block_index_rot_score()